#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDesktopWidget>
#include <QMessageBox>
#include <QStatusBar>
#include <QDockWidget>

#include <QDebug>

MainWindow::MainWindow() : ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    centerOnScreen();

    createToolBar();
    connectActions();

    plot_in = new FlowPlot;
    plot_in->setTitle("In [KB]");
    plot_in->setMaximumHeight(150);
    ui->horizontalLayout_2->addWidget(plot_in);

    plot_out = new FlowPlot;
    plot_out->setTitle("Out [KB]");
    plot_out->setMaximumHeight(150);
    ui->horizontalLayout_2->addWidget(plot_out);

    plot_in->startTimer(DEFAULT_REFRESH_TIME);
    plot_out->startTimer(DEFAULT_REFRESH_TIME);
    startTimer(DEFAULT_REFRESH_TIME);

    updateStatusBar();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *)
{
    if( not pcap.isStarted() or pcap.getCapturedPackets().empty() ) {
        plot_in->setData(0.0);
        plot_out->setData(0.0);
        return;
    }

    double last_in_total = core.getInByteS();
    double last_out_total = core.getOutByteS();

    while(not pcap.getCapturedPackets().empty()) {

        PacketHeader packet = pcap.getCapturedPackets().front();
        pcap.getCapturedPackets().pop();

        core.processPacket(packet);

    }

    // get the initiated flows to show on listwidget
    std::vector<Flow> initiated = core.getInitiatedFlows();

    QListWidget * listWidget = ui->listWidget;

    /*
    void QListWidget::clear () [slot]
    Removes all items and selections in the view.
    Warning: All items will be permanently deleted.
    */
    listWidget->clear();

    for (size_t i = 0; i < initiated.size() ; ++i) {

        Flow flow = initiated[i];

        // Hacer consulta con netstat
        // "netstat -lnpt"

        QListWidgetItem * item = new QListWidgetItem(listWidget);

        item->setIcon(QIcon(":Icons/signal_yellow.png"));

        QString source;
        source = tr("Source: ") + QString::fromStdString(flow.getSourceAddress()) + tr(":") + QString::number(flow.getSourcePort());

        QString destination;
        destination = tr("Destination: ") + QString::fromStdString(flow.getDestinationAddress()) + tr(":") + QString::number(flow.getDestinationPort());

        QString mbytes;
        mbytes = QString::number(flow.getBytes()/pow(1024,2)) + tr(" MB");

        QString text = source + tr("\n") + destination + tr("\n") + mbytes;

        item->setText(text);

    }

    double total_in_bytes = core.getInByteS();
    double total_out_bytes = core.getOutByteS();

    double in = last_in_total > total_in_bytes ? (last_in_total - total_in_bytes) : (total_in_bytes -last_in_total);
    double out = last_out_total > total_out_bytes ? (last_out_total - total_out_bytes) : (total_out_bytes -last_out_total);

    plot_in->setData(in);
    plot_out->setData(out);

    updateStatusBar();
}

void MainWindow::centerOnScreen()
{
    QSize desktop = QApplication::desktop()->size();

    int x = (desktop.width() - width()) / 2;
    int y = (desktop.height() - height()) / 2;

    setGeometry(x,y,width(),height());
}

void MainWindow::connectActions()
{
    connect(ui->actionStart_Capture,SIGNAL(triggered()),&pcap,SLOT(startCapture()));
    connect(ui->actionStop_Capture ,SIGNAL(triggered()),&pcap,SLOT(stopCapture()));

    connect(ui->actionStart_Capture,SIGNAL(toggled(bool)),comboBox,SLOT(setDisabled(bool)));
    connect(ui->actionStop_Capture,SIGNAL(toggled(bool)),comboBox,SLOT(setEnabled(bool)));

    connect(ui->actionStart_Capture,SIGNAL(triggered()),this,SLOT(test()));
}

void MainWindow::createToolBar()
{
    createComboBox();

    QToolBar * toolBar = ui->toolBar;
    toolBar->insertWidget(ui->actionStart_Capture,comboBox);

    toolBar->addWidget(new QLabel(tr("Host IP Address ")));

    lineEdit = new QLineEdit(this);
//    lineEdit->setInputMask(tr("000.000.000.000"));
    lineEdit->setMaximumWidth(100);
    lineEdit->setAlignment(Qt::AlignHCenter);
    toolBar->addWidget(lineEdit);
}

void MainWindow::createComboBox()
{
    comboBox = new QComboBox(this);
    comboBox->setIconSize(QSize(32,32));
    connect(comboBox,SIGNAL(currentIndexChanged(QString)),&pcap,SLOT(setInterfaceName(QString)));

    QList<Interface> interfaces = pcap.getInterfaces();

    QIcon wifiIcon(":Icons/wifi_modem.png");
    QIcon ethIcon(":Icons/ethernet_card.png");

    foreach(Interface interface,interfaces) {

        if(interface.datalink_type == DLT_IEEE802_11)  /* Wifi */
            comboBox->addItem(wifiIcon,interface.name);

        if(interface.datalink_type == DLT_EN10MB)      /* Ethernet 10MB */
            comboBox->addItem(ethIcon,interface.name);

    }
}

void MainWindow::updateStatusBar()
{
    double den = pow( 1024 , 2 );

    double in_mbytes  = core.getInByteS()  / den;
    double out_mbytes = core.getOutByteS() / den;

    long count = core.getPacketsCount();

    QString in_bytes_string  = QString::number(in_mbytes);
    QString out_bytes_string = QString::number(out_mbytes);
    QString processed_string = QString::number(count);

    QString message = tr("In: %1 MB    Out: %2 MB    Tcp Packets: %3 ").arg(in_bytes_string,out_bytes_string,processed_string);

    QLabel * label = ui->label;
    label->setText(message);
}

void MainWindow::test()
{
    QString ip = lineEdit->text();
    core.setIp(ip.toStdString());
}
